﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using AutoMapper;
using Encryption;
using KSUNO_EMS.Models;

namespace KSUNO_EMS.Controllers
{
    public class LoginController : Controller
    {
        //
        // GET: /Login/

        public ActionResult Index(bool authenticationFailed = false)
        {
            if (!User.Identity.IsAuthenticated)
                return View(authenticationFailed);
            var userInfo = MvcApplication.GetCurrentUserInfo();
            return RedirectToAction("Index", userInfo.Role == "Manager" ? "ScheduleManagement" : "Schedule");
        }

        public ActionResult Login(string username, string password)
        {
            var passwordHash = Hash.GetHash(password, Hash.HashType.SHA256);
            using (var db = new EmsDb())
            {
                var user = db.Employees.SingleOrDefault(e => e.Username == username && e.Password == passwordHash);
                if (user != null)
                {
                    FormsAuthentication.SetAuthCookie(username, true);
                    Session[username] = Mapper.Map<Employee, EmployeeDTO>(user);
                    return RedirectToAction("Index", user.Role == "Manager" ? "ScheduleManagement" : "Schedule");
                    
//                    return RedirectToAction("Index", "EmployeeManagement");
                }
            }

            return RedirectToAction("Index", new { authenticationFailed = true });
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index");
        }

        public ActionResult Unauthorized()
        {
            return View();

        }
    }
}
